/*
   Copyright 2009 Abdulla Abdurakhmanov (abdulla@latestbit.com)
   Original sources are available at www.latestbit.com

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.latestbit.smartobjects.core;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.latestbit.smartobjects.IDestroyable;
import org.latestbit.smartobjects.ISmartBus;
import org.latestbit.smartobjects.ISmartBus.ConnectMode;
import org.latestbit.smartobjects.exceptions.IncorrectURIException;
import org.latestbit.smartobjects.network.IManagedClient;

public class SmartBusClient implements IDestroyable {
	private IManagedClient managedClient;
	private ICommandProcessor commandProcessor;
	private int reference = 0;
	private ISmartBus bus;
	
	public SmartBusClient(ISmartBus bus, IManagedClient managedClient) {
		this.bus = bus;
		this.commandProcessor = new CommandProcessor(bus);
		this.managedClient = managedClient;
		this.managedClient.addStreamListener( this.commandProcessor );
	}
	
	public IManagedClient getManagedClient() {
		return managedClient;
	}

	public ICommandProcessor getCommandProcessor() {
		return commandProcessor;
	}
	
	
	public synchronized void start() throws IncorrectURIException, IOException, InterruptedException {
		if(this.reference == 0) {
			if(bus.getConnectMode() == ConnectMode.SYNC_CONNECT_MODE) {
				this.managedClient.start(bus.getSyncConnectTimeout(), TimeUnit.SECONDS);
			}
			else
				this.managedClient.start();
		}
	}
	
	private synchronized void stop() {
		if(this.managedClient!=null)
			this.managedClient.stop();
	}	
	
	public synchronized void addRef() {
		this.reference++;
	}
	
	public synchronized boolean releaseRef() {
		if(--this.reference < 0) {
			destroy();
			return true;
		}
		else
			return false;
	}

	@Override
	public void destroy() {
		stop();
		if(this.managedClient!=null) {
			this.managedClient.delStreamListener( this.commandProcessor );
			this.managedClient.destroy();
			this.managedClient=null;	
		}
		if(this.commandProcessor!=null) {
			this.commandProcessor.destroy();
			this.commandProcessor = null;
		}
	}
	
}